import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';
@Injectable()
export class PermissionGuard implements CanActivate {
  @Inject(Reflector)
  private readonly reflector: Reflector;
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request=context.switchToHttp().getRequest();
    if(!request.user) return true
    const permissions = request.user.permissions;
    const requiredPermissions = this.reflector.getAllAndOverride<string[]>('require-permission', [
      context.getClass(),
      context.getHandler()
    ])
    console.log(permissions,'permissions');
    
    if(!requiredPermissions)  return true;
    // 检查用户权限是否满足要求
    for(let i=0;i<requiredPermissions.length;i++){
      const curPermission = requiredPermissions[i];
      const found=permissions.find(permission=>permission.code===curPermission);
      if(!found){
        throw new UnauthorizedException('权限不足')
      }
    }
    return true;
  }
}
